package com.zhengqiangblog.core;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

public class PropertiesHelper {

	private static final Logger logger = Logger.getLogger(PropertiesHelper.class);

	private static final Properties properties = new Properties();

	static {
		// 首先加载默认配置文件
		String commonProperties = getConfigBasePath() + "common.properties";
		logger.info("Loading propreties file: " + commonProperties);
		loadProperties(new File(commonProperties));
		// 然后加载主机名对应的配置文件
		String localHostName = getLocalHostName();
		if (StringUtils.isNotBlank(localHostName)) {
			String localHostProperties = getConfigBasePath() + localHostName + ".properties";
			logger.info("Loading propreties file: " + localHostProperties);
			loadProperties(new File(localHostProperties));
		}
	}

	// 加载配置文件
	private static void loadProperties(File propertiesFile) {
		try {
			InputStream in = new BufferedInputStream(new FileInputStream(propertiesFile));
			properties.load(in);
			in.close();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
	}

	// 获取主机名
	private static String getLocalHostName() {
		InetAddress localHost = null;
		try {
			localHost = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			logger.error("Can't get host name.", e);
		}
		if (localHost != null) {
			return localHost.getHostName();
		}
		return null;
	}

	// 获取properties文件的根目录
	private static String getConfigBasePath() {
		return PropertiesHelper.class.getResource("/config/").getPath();
	}

	public static Object get(Object key) {
		return properties.get(key);
	}

	public static boolean containsKey(Object key) {
		return properties.containsKey(key);
	}

}
